﻿function auditoriumScheduleViewModel(parent) {
    var self = this;

    if (parent != null)
        extend(this, parent);

    //######################### Public properties ####################################
    self.buildings = ko.observableArray([]);

    self.currentBuilding = ko.observable({Id: 1, Name: "Главный корпус"});

    self.currentAuditoriumNumber = ko.observable();

    self.currentAuditorium = ko.observable({ Number: undefined });

    self.scheduleViewModel = {
        tutorial: ko.observable(),
        tutorialType: ko.observable(),
        times: ko.observableArray([]),
        lecturers: ko.observableArray([]),
        daysOfWeek: ko.observableArray([]),
        groupCode: ko.observable(),
        lecturer: ko.observable(),
        time: ko.observable(),
        isupdate: false,

        init: function () {
            this.tutorial(undefined);
            this.tutorialType(undefined);
            this.times([]);
            this.lecturers([]);
            this.daysOfWeek([]);
            this.groupCode(undefined);
            this.lecturer(undefined);
            this.time(undefined);
            this.isupdate = false;
        },

        save: function () {
        },

        saveAndClose: function () {
        }
    };
    //######################### End public properties ################################

    //######################### Properties subscription ##############################
    self.currentBuilding.subscribe(function (newValue) {
        if (self.currentAuditoriumNumber() !== undefined)
            self.search();
    });

    self.scheduleViewModel.lecturer.subscribe(function (newValue) {
        if (newValue !== undefined) {
            if (newValue.length > 2) {
                self.loadData({
                    address: "lecturer/get",
                    params: {
                        value: newValue
                    },
                    onsuccess: function (data) {
                        $('.typeahead').autocomplete({
                            minLength: 3,
                            source: data
                        });
                    },
                    onerror: function () {
                        self.showError("Неудалось найти лектора!");
                    }
                });
            }
        }
    });

    self.times.subscribe(function newValue() {
    });
    //######################### End properties subscription ##########################

    //######################### Commands #############################################
    self.search = function () {
        self.loadData({
            address: "auditorium/getbynumber/" + self.currentAuditoriumNumber() + "/" + self.currentBuilding().Id,
            onsuccess: function (data) {
                self.currentAuditorium(data);
                self.unselectSchedule();

                self.loadData({
                    address: "schedule/getforauditorium/" + data.Id,
                    onsuccess: function (schedules) {
                        self.applySchedule(schedules)
                    }
                });
            },
            onerror: function () {
                self.applySchedule([]);
                self.currentAuditorium({ Number: undefined });
                self.showError("Неудалось загрузить расписание!");
            }
        });
    };

    self.showDialog = function (s, e) {
        self.deselectAll();

        if (self.selectedScheduleCard() === undefined)
            self.addLessonView();
        else
            self.editLessonView();
    };

    self.addLessonView = function () {
        var modal = $("#addScheduleView").modal();
        modal.on('hidden', function () {
            self.scheduleViewModel.init();
        });
    };

    self.editLessonView = function (s, e) {
    };

    self.deleteLessonView = function (s, e) {
        if(self.selectedScheduleCard() !== undefined) {
            self.sendData({
                address: "schedule/delete",
                params: {'id': self.selectedScheduleCard()},
                onsuccess: function () {
                    self.search();
                },
                onerror: function () {
                    self.showError("Неудалось удалить занятие");
                }
            });
        }
    };

    self.selectBuilding = function (s, e) {
        self.currentBuilding(s);

        $("left-menu>li.active").removeClass("active");
        $("#building" + s.Id).addClass("active");

        self.unselectSchedule();
    };

    self.scheduleTicketClick = function (s, e) {
        var currentTarget = $(e.currentTarget);

        self.selectedScheduleCard(currentTarget.attr("data-scheduleid"));

        self.scheduleViewModel.daysOfWeek([currentTarget.attr("data-dayOfWeek")]);
        self.scheduleViewModel.times([s.Id]);
        self.scheduleViewModel.time(s.Id);

        $("td.selected").removeClass("selected");
        currentTarget.addClass("selected");
    };
    //######################### End commands #########################################

    //######################### Additional functions #################################
    self.applySchedule = function (data) {
        var days = [["", "", "", "", "", "", "", "", "", ""],
                    ["", "", "", "", "", "", "", "", "", ""],
                    ["", "", "", "", "", "", "", "", "", ""],
                    ["", "", "", "", "", "", "", "", "", ""],
                    ["", "", "", "", "", "", "", "", "", ""],
                    ["", "", "", "", "", "", "", "", "", ""]];
        $.each(data, function (index, item) {

            days[item.DayOfWeek - 1][item.Period.Id - 1] = {
                Id: item.Id,
                TutorialName: item.Tutorial.Name,
                TutorialTypeName: item.TutorialType.Name,
                FacultyName: item.Group.Speciality.Department.Faculty.ShortName,
                CourseName: item.Group.Course.Name,
                GroupCode: item.Group.Code,
                Lecturer: item.Lecturer.Lastname + " " + item.Lecturer.Firstname + " " + item.Lecturer.Middlename
            };
        });

        self.schedule(days);
    }

    self.unselectSchedule = function () {
        $("td.selected").removeClass("selected");
    }
    //######################### End additional functions #############################

    // Initialize object
    this.init = function () {
        this.prototype.init.call(this);

        //if (!self.hasHash()) getData();

        self.loadData({
            address: "building/getall",
            obj: self.buildings,
            onsuccess: function () {
                $("a, button, input").tooltip({ placement: 'right' });
            }
        });

        self.applySchedule([]);
        self.updateWeekDays();

        $(".content").jScrollPane({
            autoReinitialise: true,
            topCapHeight: 20,
            bottomCapHeight: 200
        });
        $(".left-menu").jScrollPane({
            autoReinitialise: true,
            animateTo: true
        });
        $("a, button, input").tooltip({ placement: 'top' });
        $("select").tooltip({ placement: 'top' });
        $("#emptyAuditoriumNum").modal({ backdrop: false, keyboard: false });

        $("#searchTextBox").autoNumeric({ vMin: 1, vMax: 599 });
    };
}

$(function () {
    var schedule = new auditoriumScheduleViewModel(baseViewModel);

    schedule.init();

    ko.applyBindings(schedule);
})